import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Card, Form, Button, Input, Select, Table, Space } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import {
  reqHospitalList,
  reqGetProvince,
  reqCityOrDistrict,
} from '@api/hospital/hospitalList'
import {
  IhospitalListParams,
  IhospitalList,
  IhospitalListResItem,
  IprovinceList,
  IhospitalListResponse,
} from '@api/hospital/model/hospitalListTypes'
import { Navigate } from 'react-router-dom'
const { Option } = Select

let isSearch = false // 用于区分查询表格数据时,是否要有筛选条件
export default function HospitalList() {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const [total, setTotal] = useState(50)
  const [hospitalList, setHospitalList] = useState<IhospitalList>([])

  // 省数据
  const [province, setProvince] = useState<IprovinceList>([])
  //市数据
  const [city, setCity] = useState<IprovinceList>([])
  //区数据
  const [district, setDistrict] = useState<IprovinceList>([])
  // 医院等级
  const [hospitalOrder, setHospitalOrder] = useState<IprovinceList>([])

  //分页相关的状态
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(2)
  // 组件挂载的时候,获取表格数据
  useEffect(() => {
    // 获取表格中的数据
    getHospitalList(page, pageSize)

    // 获取省数据
    getProvince()
    // 获取医院等级数据
    getHospitalOrder()
  }, [])

  // 获取表格数据的方法
  async function getHospitalList(page: number, limit: number) {
    setPage(page)
    setPageSize(limit)
    // 封装的axios发送请求的方法
    let result: IhospitalListResponse
    if (isSearch) {
      // 需要有筛选条件
      // 获取表单中的数据
      const {
        hosname,
        hoscode,
        hostype,
        provinceCode,
        cityCode,
        districtCode,
        status,
      } = form.getFieldsValue()
      // 发送请求的时候,传入筛选条件
      result = await reqHospitalList({
        page,
        limit,
        hosname,
        hoscode,
        hostype,
        provinceCode,
        cityCode,
        districtCode,
        status,
      })
    } else {
      //不需要有筛选条件
      result = await reqHospitalList({ page, limit })
    }

    // console.log(result)
    setTotal(result.totalElements)
    setHospitalList(result.content)
  }

  // 获取省数据的方法
  async function getProvince() {
    const result = await reqGetProvince()
    // console.log(result)
    setProvince(result)
  }

  // 获取市数据的方法
  async function getCity(provinceId: string) {
    // 清空市和区选择的数据
    form.setFieldsValue({ cityCode: undefined, districtCode: undefined })
    // 获取市数据
    const result = await reqCityOrDistrict(provinceId)
    // console.log(result)
    setCity(result)
  }
  // 获取区数据的方法
  async function getDistrict(cityId: string) {
    // 清空区选择的数据
    form.setFieldsValue({ districtCode: undefined })
    const result = await reqCityOrDistrict(cityId)
    // console.log(result)
    setDistrict(result)
  }

  // 获取医院等级数据的函数
  async function getHospitalOrder() {
    const result = await reqCityOrDistrict('10000')
    setHospitalOrder(result)
  }

  // 查询按钮的事件处理函数
  const onFinish = () => {
    isSearch = true //标记一下,后面再发请求,要带筛选条件
    getHospitalList(1, pageSize)
  }
  // 查询按钮的事件处理函数
  const onClear = () => {
    isSearch = false //标记一下,后面再发请求,不要带筛选条件
    // 清空表单的选项
    form.resetFields()
    getHospitalList(1, pageSize)
  }

  const columns: ColumnsType<IhospitalListResItem> = [
    {
      title: '序号',
      render: (text, records, index) => index + 1,
      align: 'center',
    },
    {
      title: '医院logo',
      render: (data) => {
        return (
          <img
            src={'data:image/png;base64,' + data.logoData}
            alt=""
            width="80"
          />
        )
      },
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      render(data) {
        return data.param.hostypeString
      },
    },
    {
      title: '详细地址',
      render(data) {
        return data.param.fullAddress
      },
    },
    {
      title: '状态',
      render(data) {
        return data.status ? '已上线' : '未上线'
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',

      render: (data) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={() => {
              navigate('/syt/hospital/hospitalList/show', {
                state: data.id,
              })
            }}
          >
            查看
          </Button>
          <Button
            type="primary"
            onClick={() => {
              navigate(`/syt/hospital/hospitalList/schedule/${data.hoscode}`)
            }}
          >
            排班
          </Button>
          <Button type="primary">{data.status ? '下' : '上'}线</Button>
        </Space>
      ),
    },
  ]
  return (
    <Card>
      <Form layout="inline" form={form} onFinish={onFinish}>
        <Form.Item name="provinceCode">
          <Select
            style={{ width: 200 }}
            placeholder="请选择省"
            onChange={getCity}
          >
            {province.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode">
          <Select
            style={{ width: 200 }}
            placeholder="请选择市"
            onChange={getDistrict}
          >
            {city.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode">
          <Select style={{ width: 200 }} placeholder="请选择区">
            {district.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="hosname">
          <Input placeholder="医院名称"></Input>
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编码"></Input>
        </Form.Item>
        <Form.Item name="hostype">
          <Select style={{ width: 200, marginTop: 10 }} placeholder="医院类型">
            {hospitalOrder.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="status">
          <Select style={{ width: 200, marginTop: 10 }} placeholder="医院状态">
            <Option value={0}>未上线</Option>
            <Option value={1}>已上线</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button
            htmlType="submit"
            type="primary"
            style={{ marginTop: 10 }}
            icon={<SearchOutlined />}
          >
            查询
          </Button>
        </Form.Item>
        <Form.Item>
          <Button style={{ marginTop: 10 }} onClick={onClear}>
            清空
          </Button>
        </Form.Item>
      </Form>
      <Table
        rowKey={'id'}
        columns={columns}
        dataSource={hospitalList}
        style={{ marginTop: 20 }}
        bordered
        pagination={{
          total,
          current: page,
          pageSize,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['2', '5', '10'],
          onChange: getHospitalList,
        }}
      />
    </Card>
  )
}
